package dnet

/*
  发送尚未完成
*/
import (
	"dgo/goutils/utils"
	"fmt"
	"net"
)

type BlockTcpClient struct {
	conn net.Conn
}

func NewBlockTcpClient() *BlockTcpClient {
	rval := &BlockTcpClient{}
	return rval
}

func (this *BlockTcpClient) Connect(remoteAddr string) bool {
	conn, err := net.Dial("tcp", remoteAddr)
	if err != nil {
		utils.Log.Errf("%v", err)
		return false
	}

	this.conn = conn
	return true
}

func (this *BlockTcpClient) Close() {
	if this.conn != nil {
		this.conn.Close()
	}
}

func (this *BlockTcpClient) Read(buffer []byte) (int, error) {
	if this.conn == nil {
		return -1, fmt.Errorf("连接建立尚未成功")
	}
	return this.conn.Read(buffer)
}

func (this *BlockTcpClient) SendBuffer(buffer []byte) bool {
	if this.conn == nil {
		utils.Log.Errf("连接建立尚未成功.")
		return false
	}
	_, err := this.conn.Write(buffer)
	if err != nil {
		utils.Log.Info(this.conn.RemoteAddr().String(), " 处理发送数据时出现了异常:", err)
		return false
	}
	return true
}
